package com.webserver.http;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * HTTP请求对象
 * 该类的每一个实例用于表示一个HTTP请求内容
 * 每个请求由三部分构成:
 * 请求行，消息头，消息正文
 */
public class HttpServletRequest {
    private Socket socket;
    //请求行相关信息
    private String method;//请求方式
    private String uri;//抽象路径
    private String protocol;//协议版本

    private String requsetURI;
    private String queryString;

    private Map<String,String> parameters = new HashMap<>();

    //消息头相关信息
    private Map<String,String> headers = new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException, EmptyRequsetException {
        this.socket = socket;
        //1.1解析请求行
        parseRequestLine();
        //1.2解析消息头
        parseHeaders();
        //1.3解析消息正文
        parseContent();
    }

    /**
     * 解析请求行
     */
    private void parseRequestLine() throws IOException, EmptyRequsetException {
        String line = readLine();

        if(line.isEmpty()){
            throw new EmptyRequsetException();
        }

        System.out.println(line);

        String[] array = line.split("\\s");
        method = array[0];
        uri = array[1];//这里可能会出现数组下标越界异常!原因:浏览器空请求，后期会解决
        protocol = array[2];

        //进一步解析uri
        parseUri();

        System.out.println("method:"+method);         //GET
        System.out.println("uri:"+uri);               // /myweb/index.html
        System.out.println("protocol:"+protocol);     //HTTP/1.1
    }

    /**
     * 进一步解析uri
     */
    private void parseUri(){

        String[] arr = uri.split("\\?");
        requsetURI = arr[0];
        if(arr.length>1){
            queryString = arr[1];
            //进一步拆分参数部分
            parseParameter(queryString);
        }

        System.out.println("requsetURI:"+requsetURI);
        System.out.println("queryString:"+queryString);
        System.out.println("parameters:"+parameters);
    }

    /**
     * 解析消息头
     */
    private void parseHeaders() throws IOException {
        while (true) {
            String line = readLine();
            if(line.isEmpty()){
                break;
            }
            System.out.println("消息头:"+line);

            String[] key_value = line.split(":\\s");
            headers.put(key_value[0].toLowerCase(),key_value[1]);
        }
        System.out.println("headers:"+headers);

//            while (!(line = readLine()).isEmpty()) {
//                System.out.println("消息头:"+line);
//            }
    }

    /**
     * 解析消息正文
     */
    private void parseContent() throws IOException {
        //当一个请求的请求方式为POST时，则说明应当会包含消息正文
        if("post".equalsIgnoreCase(method)){
            //消息头中是否含有Content-Length
            if(headers.containsKey("content-length")){
                int contentLength = Integer.parseInt(headers.get("content-length"));
                System.out.println("------"+contentLength+"------");

                byte[] data = new byte[contentLength];
                InputStream in = socket.getInputStream();
                in.read(data);

                //根据消息头Content-Type判断正文类型并进行对应的解析
                if(headers.containsKey("content-type")){
                    String contentType = headers.get("content-type");
                    System.out.println("------"+contentType+"------");
                    //如果正文类型为form表单提交类型
                    if("application/x-www-form-urlencoded".equals(contentType)){
                        String line = new String(data, StandardCharsets.ISO_8859_1);
                        System.out.println("正文内容:"+line);
                        parseParameter(line);
                    }
                    //else if("xxx/xxx".equals(contentType)){}//后期可扩展

                }
            }

        }

    }

    /**
     * 解析参数，参数的格式应当是:name1=value1&name2=value2&...
     * 将每一组参数的参数名作为key，参数值作为value存入parameters中
     * @param line
     */
    private void parseParameter(String line){
        try {
            line = URLDecoder.decode(line,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] data = line.split("&");
        //遍历数组，再进一步拆分每一个参数
        for(String s : data){
            String[] key_value = s.split("=");
            parameters.put(key_value[0],key_value.length>1?key_value[1]:null);
        }
    }

    /**
     * 通过socket获取的输入流读取客户端发送过来的一行字符串
     * @return
     */
    private String readLine() throws IOException {
        //读取客户端发过来的消息
        InputStream in = socket.getInputStream();

        char pre = 'a', cur = 'a';//pre上次读取的字符，cur本次读取的字符
        StringBuilder builder = new StringBuilder();
        int d;
        while ((d = in.read())!=-1) {
            cur = (char)d;//本次读取到的字符
            if(pre == 13 && cur == 10){//判断是否连续读取到了回车和换行符
                break;
            }
            builder.append(cur);
            pre = cur;//在进行下次读取字符前将本次读取的字符记作上次读取的字符
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name){
        return headers.get(name.toLowerCase());
    }

    public String getRequsetURI() {
        return requsetURI;
    }

    public String getQueryString() {
        return queryString;
    }

    public String getParameter(String name){
        return parameters.get(name);
    }

    public Map<String,String> getParameters(){
        return new HashMap(parameters);//复制一个Map返回，保证封装性
    }
}
